package org.testtools.connector.impl;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HTTPConnector {

  private static final String METHOD_POST = "POST";

  private static final String CT_APP_SOAP_XML = "application/soap+xml";

  public final static String CONTENT_TYPE = "Content-Type";

  public final static String SOAP_ACTION = "SOAPAction";

  private String url;

  private String contentType;

  private String method;

  public HTTPConnector(String url, String contentType, String method) {
    this.url = url;
    this.contentType = contentType;
    this.method = method;
  }

  // TODO JUnit
  public HttpURLConnection getConnection() throws MalformedURLException, IOException {
    return getConnection(this.url, this.contentType, this.method);
  }

  // TODO JUnit
  public static HttpURLConnection getConnection(String url, String contentType)
      throws MalformedURLException, IOException {
    return getConnection(url, contentType, null);
  }

  // TODO JUnit
  public static HttpURLConnection getConnection(String url) throws MalformedURLException,
      IOException {
    return getConnection(url, null, null);
  }

  // TODO JUnit
  public static HttpURLConnection getConnection(String url, String contentType, String method)
      throws MalformedURLException, IOException {

    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    conn.setChunkedStreamingMode(5000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method == null ? METHOD_POST : method);
    conn.setRequestProperty(CONTENT_TYPE, contentType == null ? CT_APP_SOAP_XML : contentType);

    return conn;
  }
}
